<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {

    public function speaking($n, $s=false){
        if (intval($n)<7 & intval($n) >0){
            $speakingDB = D('speaking');
            $this->assign('ques', $this->getQuestion($s, 'sq'.$n, $speakingDB, $n));
            $this->display('s'.$n);
        }else{
            $this->error('参数错误！');
        }
    }

    public function writing($n, $s=false){
        if (intval($n)<3 & intval($n) >0){
            $writingDB = D('writing');
            $this->assign('ques', $this->getQuestion($s, 'wq'.$n, $writingDB, $n));
            $this->display('w'.$n);
        }else{
            $this->error('参数错误！');
        }
    }

    private function getQuestion($source, $datapool, $database, $q){
        if (!$source){
            $ques = $this->getUniqQuestion($datapool, $database, $q);
        }else{
            $map = array('source' => $source, );
            $ques = $database->where($map)->select();
        }
        
        if($ques){
            $ques = $ques[0];
        }

        return $ques;
    }
    private function getUniqQuestion($datapool, $database, $q){
        //$questionPool = F($datapool);
        if (!$questionPool){
            $q1Set = $database->where('q='.intval($q))->getField('id', true);
            $questionPool = $q1Set;
            if (!count($questionPool)){
                $this->error('数据不够，请先录入题目！');
            }
            F($datapool, $q1Set);
        }
        $doneQ = session($datapool);
        if (!$doneQ || count($doneQ) == count($questionPool)){
            $doneQ = array();
        }
        $questionPoolN = array_diff($questionPool, $doneQ);
        shuffle($questionPoolN);
        $index = $questionPoolN[0];
        $doneQ[] = $index;
        $ques = $database->where('id='.$index)->select();
        session($datapool, $doneQ);
        return $ques;
    }
}